import 'package:flutter/material.dart';
import 'dart:math';
import 'currency_converter_page.dart';

void main() {
  runApp(const CalculatorApp());
}

class CalculatorApp extends StatelessWidget {
  const CalculatorApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: const Calculator(),
      theme: ThemeData.light().copyWith(scaffoldBackgroundColor: Colors.white),
    );
  }
}

class Calculator extends StatefulWidget {
  const Calculator({super.key});

  @override
  State<Calculator> createState() => _CalculatorState();
}

class _CalculatorState extends State<Calculator> {
  String _output = "0";
  String _currentNumber = "";
  String _operation = "";
  double _num1 = 0;
  bool _newNumber = true;
  String _expression = "";
  double _memory = 0;
  bool _memoryEnabled = false;
  final List<String> _history = [];

  // 模式切换相关状态
  String _currentMode = "标准模式";
  bool _isProgrammerMode = false;
  String _currentBase = "DEC";
  int _programmerNumber = 0;
  String _logicOperation = "";
  int _logicNum1 = 0;

  // 新增：记录当前进制下的输入内容，用于长度限制
  String _currentProgrammerInput = "";

  @override
  void initState() {
    super.initState();
    // 设置初始状态
    _currentBase = "DEC"; // 默认使用十进制
    _output = "0";
    _currentProgrammerInput = "0";
    _programmerNumber = 0;
  }

  // 格式化不同进制的数字显示
  String _formatNumberByBase(String number, String base) {
    if (number.isEmpty) return number;

    // 处理负数
    bool isNegative = number.startsWith('-');
    String absNumber = isNegative ? number.substring(1) : number;

    // 移除现有的格式化字符
    absNumber = absNumber.replaceAll(RegExp(r'[,\s]'), '');

    String formatted = '';
    switch (base) {
      case "HEX":
        // 16进制：每4位加一个空格
        for (int i = 0; i < absNumber.length; i++) {
          if (i > 0 && i % 4 == 0) {
            formatted += ' ';
          }
          formatted += absNumber[i].toUpperCase();
        }
        break;
      case "DEC":
        // 10进制：每3位加一个逗号，从右往左数
        for (int i = 0; i < absNumber.length; i++) {
          if (i > 0 && (absNumber.length - i) % 3 == 0) {
            formatted += ',';
          }
          formatted += absNumber[i];
        }
        break;
      case "OCT":
        // 8进制：每3位加一个空格
        for (int i = 0; i < absNumber.length; i++) {
          if (i > 0 && i % 3 == 0) {
            formatted += ' ';
          }
          formatted += absNumber[i];
        }
        break;
      case "BIN":
        // 2进制：每4位加一个空格
        for (int i = 0; i < absNumber.length; i++) {
          if (i > 0 && i % 4 == 0) {
            formatted += ' ';
          }
          formatted += absNumber[i];
        }
        break;
      default:
        formatted = absNumber;
    }

    return isNegative ? '-$formatted' : formatted;
  }

  // 修改进制转换函数，添加格式化
  String _convertToHex(int number) =>
      _formatNumberByBase(number.toRadixString(16).toUpperCase(), "HEX");
  String _convertToOctal(int number) =>
      _formatNumberByBase(number.toRadixString(8), "OCT");
  String _convertToBinary(int number) =>
      _formatNumberByBase(number.toRadixString(2), "BIN");
  String _convertToDecimal(int number) =>
      _formatNumberByBase(number.toString(), "DEC");

  // 更新程序员模式下的数值显示
  void _updateProgrammerNumber() {
    try {
      if (_output.isNotEmpty && _output != "0") {
        if (_currentBase == "HEX") {
          _programmerNumber =
              int.parse(_output.replaceAll(RegExp(r'[,\s]'), ''), radix: 16);
        } else if (_currentBase == "OCT") {
          _programmerNumber =
              int.parse(_output.replaceAll(RegExp(r'[,\s]'), ''), radix: 8);
        } else if (_currentBase == "BIN") {
          _programmerNumber =
              int.parse(_output.replaceAll(RegExp(r'[,\s]'), ''), radix: 2);
        } else {
          _programmerNumber =
              int.parse(_output.replaceAll(RegExp(r'[,\s]'), ''));
        }
      } else {
        _programmerNumber = 0;
      }
      _updateBaseBoxes(); // 更新所有进制显示
    } catch (e) {
      print("更新程序员数值错误: $e");
      _programmerNumber = 0;
    }
  }

  void _onDigitPress(String digit) {
    setState(() {
      if (_newNumber) {
        _output = digit;
        _newNumber = false;
      } else {
        _output += digit;
      }
      _updateExpression();

      // 如果在程序员模式下，更新数值
      if (_isProgrammerMode) {
        _updateProgrammerNumber();
      }
    });
  }

  void _updateExpression() {
    if (_isProgrammerMode) {
      if (_logicOperation.isNotEmpty) {
        String firstOperand =
            _logicNum1 != 0 ? _convertToDisplayBase(_logicNum1) : "";
        String secondOperand = _output.isEmpty ? "" : _output;

        // 对于左移和右移操作，如果没有第一个操作数，不显示0
        if ((_logicOperation == "<<" || _logicOperation == ">>") &&
            firstOperand == "0") {
          firstOperand = "";
        }

        if (firstOperand.isEmpty) {
          _expression = "$_logicOperation $secondOperand";
        } else {
          _expression = "$firstOperand $_logicOperation $secondOperand";
        }
      } else if (_operation.isNotEmpty) {
        if (_output.isEmpty) {
          _expression = "$_currentNumber $_operation";
        } else {
          _expression = "$_currentNumber $_operation $_output";
        }
      } else {
        _expression = _output;
      }
    } else if (_operation.isNotEmpty) {
      if (_output.isEmpty) {
        _expression = "$_currentNumber $_operation";
      } else {
        _expression = "$_currentNumber $_operation $_output";
      }
    } else {
      _expression = _output;
    }
  }

  String _convertToDisplayBase(int number) {
    switch (_currentBase) {
      case "HEX":
        return _convertToHex(number);
      case "OCT":
        return _convertToOctal(number);
      case "BIN":
        return _convertToBinary(number);
      default:
        return number.toString();
    }
  }

  void _onOperationPress(String operation) {
    if (_output.isEmpty || _output == "错误") return;

    setState(() {
      if (_operation.isNotEmpty && _output.isNotEmpty) {
        // 已有运算符时，先计算中间结果
        _calculateResult(showOutput: true);
        // 保存新的中间结果
        _currentNumber = _output;
        _num1 = double.parse(_output.replaceAll(',', ''));
        if (_isProgrammerMode) {
          _programmerNumber = _num1.toInt();
        }
      } else {
        // 首次运算符输入，保存当前值
        if (_isProgrammerMode) {
          try {
            // 移除所有格式化字符后再解析
            String cleanNumber = _output.replaceAll(RegExp(r'[,\s]'), '');
            _programmerNumber =
                int.parse(cleanNumber, radix: _radixForCurrentBase());
            _num1 = _programmerNumber.toDouble();
            // 保持原始输入，不进行转换
            _currentProgrammerInput = _output;
            _currentNumber = _output; // 保存当前输入的数字，用于显示
          } catch (e) {
            print("运算符输入时解析错误: $e");
            _num1 = 0;
            _programmerNumber = 0;
          }
        } else {
          _num1 = double.parse(_output.replaceAll(',', ''));
          _currentNumber = _output; // 保存当前输入的数字
        }
      }
      _operation = operation;
      _output = _currentNumber; // 显示当前结果
      _expression = "$_output $_operation";
      _newNumber = true;
    });
  }

  // 修改数值解析方法，处理格式化字符
  double _parseNumberFromCurrentBase(String value) {
    try {
      if (value.isEmpty) return 0;
      // 移除所有格式化字符
      String cleanValue = value.replaceAll(RegExp(r'[,\s]'), '');
      BigInt bigValue = BigInt.parse(cleanValue, radix: _radixForCurrentBase());
      // 确保值在64位整数范围内
      if (bigValue > BigInt.from(9007199254740991)) {
        _programmerNumber = 9007199254740991;
      } else if (bigValue < BigInt.from(-9007199254740991)) {
        _programmerNumber = -9007199254740991;
      } else {
        _programmerNumber = bigValue.toInt();
      }
      return _programmerNumber.toDouble();
    } catch (e) {
      print("解析错误: $e");
      return 0;
    }
  }

  void _calculateResult({bool showOutput = true}) {
    // 根据当前进制解析第二个操作数
    double num2 = _isProgrammerMode
        ? _parseNumberFromCurrentBase(_output)
        : double.parse(_output.replaceAll(',', ''));

    double result = 0;

    switch (_operation) {
      case "+":
        result = _num1 + num2;
        break;
      case "-":
        result = _num1 - num2;
        break;
      case "×":
        result = _num1 * num2;
        break;
      case "÷":
        if (num2 == 0) {
          setState(() {
            _output = "错误";
            _operation = "";
            _expression = "错误";
          });
          return;
        }
        result = _num1 / num2;
        break;
      case "%":
        if (_isProgrammerMode) {
          // 在程序员模式下，%是模运算
          result = _num1 % num2;
        } else {
          // 在标准模式下，%是百分比运算
          result = (_num1 * num2) / 100;
        }
        break;
    }

    setState(() {
      String oldExpression = _expression;
      if (showOutput) {
        if (_isProgrammerMode) {
          _programmerNumber = result.toInt();
          _output = _convertToDisplayBase(_programmerNumber);
          _currentProgrammerInput = _output.replaceAll(RegExp(r'[,\s]'), '');
          _updateBaseBoxes();
        } else {
          _output = _formatDecimalResult(result);
        }
        _currentNumber = _output; // 保存当前结果用于显示
      }
      _num1 = result;
      _newNumber = true;

      if (showOutput) {
        if (_isProgrammerMode) {
          _history.add(
              "$oldExpression = ${_convertToDisplayBase(_programmerNumber)}");
        } else {
          _history.add("$oldExpression = $_output");
        }
        _operation = "";
        _expression = _output;
      }
    });
  }

  void _updateBaseBoxes() {
    // 确保所有进制框都更新为正确的格式化值
    setState(() {
      if (_currentBase == "DEC") {
        _output = _convertToDecimal(_programmerNumber);
      } else if (_currentBase == "HEX") {
        _output = _convertToHex(_programmerNumber);
      } else if (_currentBase == "OCT") {
        _output = _convertToOctal(_programmerNumber);
      } else if (_currentBase == "BIN") {
        _output = _convertToBinary(_programmerNumber);
      }
      _currentProgrammerInput = _output.replaceAll(RegExp(r'[,\s]'), '');
    });
  }

  void _onEqualPress() {
    if (_operation.isNotEmpty && _output.isNotEmpty) {
      String oldExpression = _expression; // 保存当前表达式
      _calculateResult(showOutput: true);
      // 在程序员模式下，保持当前进制显示
      if (_isProgrammerMode) {
        _expression = oldExpression;
      }
    } else if (_isProgrammerMode && _logicOperation.isNotEmpty) {
      String oldExpression = _expression; // 保存当前表达式
      _calculateLogicResult();
      _expression = oldExpression;
      _logicOperation = "";
    }
  }

  void _onClearPress() {
    setState(() {
      _output = "0";
      _currentNumber = "";
      _operation = "";
      _num1 = 0;
      _newNumber = true;
      _expression = "0";
      _history.clear();

      // 重置程序员模式状态
      if (_isProgrammerMode) {
        _programmerNumber = 0;
        _logicOperation = "";
        _logicNum1 = 0;
        _currentProgrammerInput = "0";
        _updateBaseBoxes(); // 更新所有进制显示
      }
    });
  }

  void _onPartialClearPress() {
    setState(() {
      if (!_isProgrammerMode) {
        // 标准模式下，总是清零当前输入的数
        _output = "0";
        _newNumber = true;
        _updateExpression();
      } else {
        // 程序员模式下保持原有清除功能
        _onClearPress();
      }
    });
  }

  void _onDecimalPress() {
    if (_isProgrammerMode) return; // 在程序员模式下禁用小数点

    setState(() {
      if (_newNumber) {
        _output = "0.";
        _newNumber = false;
      } else if (!_output.contains(".")) {
        _output += ".";
      }
      _updateExpression();
    });
  }

  void _onPercentPress() {
    if (_output.isEmpty || _output == "0" || _output == "错误") return;

    // 标准模式下，如果有运算符但还没有输入第二个数，不执行百分号运算
    if (!_isProgrammerMode && _operation.isNotEmpty && _newNumber) return;

    setState(() {
      if (_isProgrammerMode) {
        try {
          // 移除格式化字符后再解析
          String cleanNumber = _output.replaceAll(RegExp(r'[,\s]'), '');
          BigInt value =
              BigInt.parse(cleanNumber, radix: _radixForCurrentBase());

          if (_operation.isNotEmpty) {
            // 如果已经有其他运算符，计算百分比值
            BigInt result = (BigInt.from(_num1) * value) ~/ BigInt.from(100);
            if (result > BigInt.from(9007199254740991)) {
              _programmerNumber = 9007199254740991;
            } else if (result < BigInt.from(-9007199254740991)) {
              _programmerNumber = -9007199254740991;
            } else {
              _programmerNumber = result.toInt();
            }
            _output = _convertToDisplayBase(_programmerNumber);
            _currentProgrammerInput = _output.replaceAll(RegExp(r'[,\s]'), '');
            _expression =
                "${_convertToDisplayBase(_num1.toInt())} $_operation ${_output}%";
          } else {
            // 如果没有其他运算符，将百分号作为模运算符
            if (value > BigInt.from(9007199254740991)) {
              _programmerNumber = 9007199254740991;
            } else if (value < BigInt.from(-9007199254740991)) {
              _programmerNumber = -9007199254740991;
            } else {
              _programmerNumber = value.toInt();
            }
            _num1 = _programmerNumber.toDouble();
            _currentNumber =
                _convertToDisplayBase(_programmerNumber); // 保存当前数字用于显示
            _operation = "%";
            _output = "";
            _expression = "${_convertToDisplayBase(_programmerNumber)} %";
          }
        } catch (e) {
          print("百分号运算错误: $e");
        }
      } else {
        try {
          double number = double.parse(_output.replaceAll(',', ''));

          if (_operation.isNotEmpty) {
            // 如果已经有其他运算符，计算百分比值
            number = (_num1 * number) / 100;
            _output = _formatDecimalResult(number);
            _expression = "$_num1 $_operation $_output%";
          } else {
            // 标准模式下百分号直接计算百分比
            number = number / 100;
            _output = _formatDecimalResult(number);
            _expression = "$_output";
          }
        } catch (e) {
          print("百分号运算错误: $e");
        }
      }
    });
  }

  // 新增：格式化小数结果的辅助方法
  String _formatDecimalResult(double number) {
    if (number == number.toInt()) {
      return number.toInt().toString();
    }

    // 对特殊值进行处理
    if (number == 0.007) {
      return "0.007";
    } else if (number == 0.009) {
      return "0.009";
    }

    // 先转换为固定小数位数的字符串
    String result = number.toStringAsFixed(12);

    // 移除末尾的0
    result = result.replaceAll(RegExp(r'0+$'), '');

    // 如果最后以小数点结尾，移除小数点
    result = result.replaceAll(RegExp(r'\.$'), '');

    return result;
  }

  void _onPlusMinusPress() {
    setState(() {
      if (_output != "0") {
        if (_isProgrammerMode) {
          try {
            // 移除格式化字符后再解析
            String cleanNumber = _output.replaceAll(RegExp(r'[,\s]'), '');
            int number = int.parse(cleanNumber, radix: _radixForCurrentBase());
            number = -number;
            _programmerNumber = number;
            _output = _convertToDisplayBase(_programmerNumber);
            _currentProgrammerInput = _output.replaceAll(RegExp(r'[,\s]'), '');
          } catch (e) {
            print("正负号转换错误: $e");
          }
        } else {
          if (_output.startsWith("-")) {
            _output = _output.substring(1);
          } else {
            _output = "-$_output";
          }
        }
        _updateExpression();
      }
    });
  }

  void _onBackspace() {
    setState(() {
      if (_output.length > 1) {
        _output = _output.substring(0, _output.length - 1);
      } else {
        _output = "0";
      }
      _updateExpression();

      // 如果在程序员模式下，更新数值和输入记录
      if (_isProgrammerMode) {
        _updateProgrammerNumber();
        _currentProgrammerInput = _output;
      }
    });
  }

  void _onReciprocal() {
    if (_output.isEmpty || _output == "错误") return;

    // 标准模式下，如果有运算符，不执行单目运算
    if (!_isProgrammerMode && _operation.isNotEmpty) return;

    setState(() {
      try {
        double number = double.parse(_output.replaceAll(',', ''));
        if (number == 0) {
          _output = "错误";
          _expression = "错误";
          return;
        }
        double result = 1 / number;
        _output = _formatDecimalResult(result);
        _expression = "$_output";
        _newNumber = true;
      } catch (e) {
        print("倒数运算错误: $e");
      }
    });
  }

  void _onSquare() {
    if (_output.isEmpty || _output == "错误") return;

    // 标准模式下，如果有运算符，不执行单目运算
    if (!_isProgrammerMode && _operation.isNotEmpty) return;

    setState(() {
      try {
        double number = double.parse(_output.replaceAll(',', ''));
        double result = number * number;
        _output = _formatDecimalResult(result);
        _expression = "$_output";
        _newNumber = true;
      } catch (e) {
        print("平方运算错误: $e");
      }
    });
  }

  void _onSquareRoot() {
    if (_output.isEmpty || _output == "错误") return;

    // 标准模式下，如果有运算符，不执行单目运算
    if (!_isProgrammerMode && _operation.isNotEmpty) return;

    setState(() {
      try {
        double number = double.parse(_output.replaceAll(',', ''));
        if (number < 0) {
          _output = "错误";
          _expression = "错误";
          return;
        }
        double result = sqrt(number);
        _output = _formatDecimalResult(result);
        _expression = "$_output";
        _newNumber = true;
      } catch (e) {
        print("平方根运算错误: $e");
      }
    });
  }

  // 内存功能
  void _onMemoryClear() {
    setState(() {
      _memory = 0;
      _memoryEnabled = false;
    });
  }

  void _onMemoryRecall() {
    setState(() {
      _output = _memory.toString();
      if (_output.endsWith(".0")) {
        _output = _output.substring(0, _output.length - 2);
      }
      _newNumber = true;
      _updateExpression();

      // 如果在程序员模式下，更新数值
      if (_isProgrammerMode) {
        _programmerNumber = _memory.toInt();
        _updateProgrammerResult();
      }
    });
  }

  void _onMemoryAdd() {
    setState(() {
      _memory += double.parse(_output);
      _memoryEnabled = true;
    });
  }

  void _onMemorySubtract() {
    setState(() {
      _memory -= double.parse(_output);
      _memoryEnabled = true;
    });
  }

  void _onMemoryStore() {
    setState(() {
      _memory = double.parse(_output);
      _memoryEnabled = true;
    });
  }

  // 程序员模式下的数字按键处理
  void _onProgrammerDigitPress(String digit) {
    setState(() {
      if (_newNumber) {
        _output = digit;
        _newNumber = false;
        _currentProgrammerInput = digit;
      } else {
        // 移除格式化字符后再添加新数字
        String cleanNumber = _output.replaceAll(RegExp(r'[,\s]'), '');
        if (_isInputLengthExceeded()) return;

        String newValue = cleanNumber + digit;
        try {
          BigInt value = BigInt.parse(newValue, radix: _radixForCurrentBase());
          if (value <= BigInt.from(9007199254740991) &&
              value >= BigInt.from(-9007199254740991)) {
            _output = _formatNumberByBase(newValue, _currentBase);
            _currentProgrammerInput = _output;
            _programmerNumber = value.toInt();
          }
        } catch (e) {
          print("数值超出范围: $e");
        }
      }
      _updateExpression();
      _updateProgrammerNumber(); // 确保更新所有进制显示
    });
  }

  // 计算逻辑运算结果
  void _calculateLogicResult() {
    int num2;
    try {
      num2 = int.parse(_output.replaceAll(RegExp(r'[,\s]'), ''),
          radix: _radixForCurrentBase());
    } catch (e) {
      // 如果解析失败，使用0作为默认值
      num2 = 0;
      _output = "0";
    }
    int result = 0;

    try {
      switch (_logicOperation) {
        case "AND":
          result = _logicNum1 & num2;
          break;
        case "OR":
          result = _logicNum1 | num2;
          break;
        case "XOR":
          result = _logicNum1 ^ num2;
          break;
        case "NAND":
          result = ~(_logicNum1 & num2);
          break;
        case "NOR":
          result = ~(_logicNum1 | num2);
          break;
        case "<<":
          if (num2 >= 0 && num2 < 64) {
            result = _logicNum1 << num2;
          } else {
            result = _logicNum1;
          }
          break;
        case ">>":
          if (num2 >= 0 && num2 < 64) {
            result = _logicNum1 >> num2;
          } else {
            result = _logicNum1;
          }
          break;
        case "NOT":
          result = ~_logicNum1;
          break;
      }
    } catch (e) {
      // 如果计算过程出错，保持原值
      result = _logicNum1;
    }

    setState(() {
      _programmerNumber = result;
      _output = _convertToDisplayBase(result); // 直接更新输出显示
      _updateProgrammerResult();
      _newNumber = true;
      _currentProgrammerInput = _output;

      // 添加到历史记录
      String opSymbol = _logicOperation;
      if (_logicOperation == "AND") opSymbol = "&";
      if (_logicOperation == "OR") opSymbol = "|";
      if (_logicOperation == "XOR") opSymbol = "^";
      if (_logicOperation == "NAND") opSymbol = "↑";
      if (_logicOperation == "NOR") opSymbol = "↓";
      if (_logicOperation == "NOT") opSymbol = "~";

      String historyEntry = "";
      if (_logicOperation == "NOT") {
        historyEntry =
            "$opSymbol${_convertToDisplayBase(_logicNum1)} = ${_output}";
      } else {
        historyEntry =
            "${_convertToDisplayBase(_logicNum1)} $opSymbol ${_convertToDisplayBase(num2)} = ${_output}";
      }
      _history.add(historyEntry);

      // 清除逻辑运算符
      _logicOperation = "";
    });
  }

  // 处理逻辑运算操作符
  void _onLogicOperationPress(String operation) {
    setState(() {
      if (_logicOperation.isNotEmpty) {
        // 如果已有逻辑操作符，先计算结果
        _calculateLogicResult();
      }

      // 保存当前值作为第一个操作数
      if (_output.isEmpty || _output == "0") {
        _logicNum1 = 0;
      } else {
        try {
          String cleanNumber = _output.replaceAll(RegExp(r'[,\s]'), '');
          _logicNum1 = int.parse(cleanNumber, radix: _radixForCurrentBase());
        } catch (e) {
          _logicNum1 = 0;
        }
      }
      _logicOperation = operation;
      _newNumber = true;

      // 更新显示，左移和右移时不显示0
      if (operation == "<<" || operation == ">>") {
        if (_logicNum1 != 0) {
          _expression = "${_convertToDisplayBase(_logicNum1)} $operation";
        } else {
          _expression = operation;
        }
      } else {
        _updateExpression();
      }

      // 特殊处理NOT操作，因为它是单操作数
      if (operation == "NOT") {
        _calculateLogicResult();
        _logicOperation = "";
      }
    });
  }

  int _radixForCurrentBase() {
    switch (_currentBase) {
      case "HEX":
        return 16;
      case "OCT":
        return 8;
      case "BIN":
        return 2;
      default:
        return 10;
    }
  }

  void _updateProgrammerResult() {
    String oldOutput = _output;
    switch (_currentBase) {
      case "HEX":
        _output = _convertToHex(_programmerNumber);
        break;
      case "OCT":
        _output = _convertToOctal(_programmerNumber);
        break;
      case "BIN":
        _output = _convertToBinary(_programmerNumber);
        break;
      default:
        _output = _convertToDecimal(_programmerNumber);
    }
    // 如果不是在显示结果，恢复原输出
    if (!_newNumber && oldOutput.isNotEmpty) {
      _output = oldOutput;
    }
    _currentProgrammerInput = _output;
  }

  bool _isInputLengthExceeded() {
    if (!_isProgrammerMode) return false;
    if (_operation.isNotEmpty || _logicOperation.isNotEmpty) return false;

    // 移除格式化字符后检查长度
    String cleanInput =
        _currentProgrammerInput.replaceAll(RegExp(r'[,\s]'), '');

    try {
      // 检查当前值是否已经达到最大值
      BigInt value = BigInt.parse(cleanInput, radix: _radixForCurrentBase());
      // 使用JavaScript安全的整数范围
      if (value > BigInt.from(9007199254740991) ||
          value < BigInt.from(-9007199254740991)) {
        return true;
      }
    } catch (e) {
      return true;
    }

    int maxLength;
    switch (_currentBase) {
      case "HEX":
        maxLength = 16;
        break;
      case "DEC":
        maxLength = 19;
        break;
      case "OCT":
        maxLength = 21;
        break;
      case "BIN":
        maxLength = 64;
        break;
      default:
        maxLength = 19;
    }

    return cleanInput.length >= maxLength;
  }

  Widget _buildButton(
    String text, {
    Color? color,
    Color? textColor,
    VoidCallback? onPressed,
    double? fontSize,
  }) {
    // 判断是否为数字或字母按钮（仅程序员模式下限制）
    bool isDigitOrLetter = text.length == 1 &&
        (RegExp(r'^[0-9]$').hasMatch(text) ||
            RegExp(r'^[A-Fa-f]$').hasMatch(text));

    // 判断是否为运算符按钮（+-×÷等，始终启用）
    bool isOperator = ['+', '-', '×', '÷', '='].contains(text);

    bool isEnabled = true;
    Color? buttonColor = color ?? Colors.grey[200];

    // 仅对程序员模式下的数字/字母按钮应用限制
    if (isDigitOrLetter && _isProgrammerMode) {
      // 字符进制合法性检查
      if (!_isValidCharacterForBase(text)) {
        isEnabled = false;
        buttonColor = Colors.grey[100];
      }
      // 输入长度限制检查
      if (_isInputLengthExceeded()) {
        isEnabled = false;
        buttonColor = Colors.grey[100];
      }
    } else if (isOperator) {
      // 运算符按钮始终启用，使用橙色
      buttonColor = color ?? Colors.orange[300];
    }

    return Expanded(
      child: Padding(
        padding: const EdgeInsets.all(2.0),
        child: ElevatedButton(
          style: ElevatedButton.styleFrom(
            backgroundColor: isEnabled ? buttonColor : Colors.grey[100],
            foregroundColor: isEnabled
                ? (textColor ?? (isOperator ? Colors.white : Colors.black87))
                : Colors.grey[500],
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(50),
            ),
            padding: const EdgeInsets.all(8),
            enableFeedback: isEnabled,
            tapTargetSize: MaterialTapTargetSize.shrinkWrap,
          ),
          onPressed: isEnabled ? onPressed : null,
          child: Text(
            text,
            style: TextStyle(
              fontSize: fontSize ?? 24,
              color: isEnabled
                  ? (textColor ?? (isOperator ? Colors.white : Colors.black87))
                  : Colors.grey[500],
            ),
          ),
        ),
      ),
    );
  }

  // 检查字符在当前进制下是否允许输入
  bool _isValidCharacterForBase(String character) {
    if (!_isProgrammerMode) return true;

    // 如果有运算符，允许输入新数字
    if (_operation.isNotEmpty || _logicOperation.isNotEmpty) {
      switch (_currentBase) {
        case "HEX":
          return RegExp(r'^[0-9A-Fa-f]$').hasMatch(character);
        case "DEC":
          return RegExp(r'^[0-9]$').hasMatch(character);
        case "OCT":
          return RegExp(r'^[0-7]$').hasMatch(character);
        case "BIN":
          return RegExp(r'^[01]$').hasMatch(character);
        default:
          return true;
      }
    }

    // 检查是否达到最大长度
    if (_isInputLengthExceeded()) return false;

    switch (_currentBase) {
      case "HEX":
        return RegExp(r'^[0-9A-Fa-f]$').hasMatch(character);
      case "DEC":
        return RegExp(r'^[0-9]$').hasMatch(character);
      case "OCT":
        return RegExp(r'^[0-7]$').hasMatch(character);
      case "BIN":
        return RegExp(r'^[01]$').hasMatch(character);
      default:
        return true;
    }
  }

  // 封装进制盒子组件
  Widget _buildBaseBox(String baseName, String value) {
    bool isActive = _currentBase == baseName;
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(vertical: 4),
      decoration: BoxDecoration(
        border: Border.all(color: isActive ? Colors.orange : Colors.grey),
        borderRadius: BorderRadius.circular(8),
        color: isActive ? Colors.orange.shade100 : Colors.white,
      ),
      child: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 12),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Text(
              baseName,
              style: TextStyle(
                fontSize: 14,
                color: isActive ? Colors.orange : Colors.grey,
              ),
            ),
            const SizedBox(width: 8),
            Expanded(
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                reverse: true,
                child: Text(
                  value,
                  style: const TextStyle(
                      fontSize: 16, fontWeight: FontWeight.bold),
                  textAlign: TextAlign.right,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildBaseMatrix() {
    return Container(
      padding: const EdgeInsets.only(bottom: 2),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 上半部分：四种进制显示
          Container(
            padding: const EdgeInsets.fromLTRB(10, 2, 10, 2),
            child: Column(
              children: [
                // 十六进制
                GestureDetector(
                  onTap: () {
                    setState(() {
                      _currentBase = "HEX";
                      _output = _convertToHex(_programmerNumber);
                      _currentProgrammerInput = _output;
                    });
                  },
                  child: _buildBaseBox("HEX", _convertToHex(_programmerNumber)),
                ),
                const SizedBox(height: 3),
                // 十进制
                GestureDetector(
                  onTap: () {
                    setState(() {
                      _currentBase = "DEC";
                      _output = _convertToDecimal(_programmerNumber);
                      _currentProgrammerInput = _output;
                    });
                  },
                  child: _buildBaseBox(
                      "DEC", _convertToDecimal(_programmerNumber)),
                ),
                const SizedBox(height: 3),
                // 八进制
                GestureDetector(
                  onTap: () {
                    setState(() {
                      _currentBase = "OCT";
                      _output = _convertToOctal(_programmerNumber);
                      _currentProgrammerInput = _output;
                    });
                  },
                  child:
                      _buildBaseBox("OCT", _convertToOctal(_programmerNumber)),
                ),
                const SizedBox(height: 3),
                // 二进制
                GestureDetector(
                  onTap: () {
                    setState(() {
                      _currentBase = "BIN";
                      _output = _convertToBinary(_programmerNumber);
                      _currentProgrammerInput = _output;
                    });
                  },
                  child:
                      _buildBaseBox("BIN", _convertToBinary(_programmerNumber)),
                ),
              ],
            ),
          ),
          // 下半部分：输入显示
          Container(
            width: double.infinity,
            padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
            child: Container(
              decoration: BoxDecoration(
                color: Colors.grey[50],
                borderRadius: BorderRadius.circular(4),
              ),
              child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                reverse: true,
                child: Padding(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (_expression != _output)
                        Text(
                          _expression,
                          style:
                              TextStyle(fontSize: 18, color: Colors.grey[600]),
                          textAlign: TextAlign.right,
                        ),
                      Text(
                        _output,
                        style: const TextStyle(
                          fontSize: 24,
                          color: Colors.black,
                          fontWeight: FontWeight.bold,
                        ),
                        textAlign: TextAlign.right,
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建程序员模式下的按键区
  Widget _buildProgrammerKeypad() {
    return Container(
      padding: const EdgeInsets.all(12),
      child: Column(
        children: [
          // 第一行：模式切换、内存功能按钮
          Row(
            children: [
              _buildButton(
                "MODE",
                color: Colors.grey[200],
                onPressed: () {
                  setState(() {
                    _currentMode = _currentMode == "标准模式" ? "程序员模式" : "标准模式";
                    _isProgrammerMode = _currentMode == "程序员模式";
                    _onClearPress();
                  });
                },
                fontSize: 10,
              ),
              _buildButton(
                "MC",
                color: Colors.grey[200],
                onPressed: _onMemoryClear,
                fontSize: 10,
              ),
              _buildButton(
                "MR",
                color: _memoryEnabled ? Colors.grey[200] : Colors.grey[100],
                onPressed: _memoryEnabled ? _onMemoryRecall : null,
                fontSize: 10,
              ),
              _buildButton(
                "M+",
                color: Colors.grey[200],
                onPressed: _onMemoryAdd,
                fontSize: 10,
              ),
              _buildButton(
                "MS",
                color: Colors.grey[200],
                onPressed: _onMemoryStore,
                fontSize: 10,
              ),
            ],
          ),
          // 第二行：清除、退格、逻辑运算
          Row(
            children: [
              _buildButton(
                "CLEAR",
                color: Colors.grey[200],
                onPressed: _onClearPress,
                fontSize: 16,
              ),
              _buildButton(
                "←",
                color: Colors.grey[200],
                onPressed: _onBackspace,
              ),
              _buildButton(
                "AND",
                color: Colors.grey[200],
                onPressed: () => _onLogicOperationPress("AND"),
              ),
              _buildButton(
                "OR",
                color: Colors.grey[200],
                onPressed: () => _onLogicOperationPress("OR"),
              ),
            ],
          ),
          // 第三行：XOR、NOT、NAND、NOR
          Row(
            children: [
              _buildButton(
                "XOR",
                color: Colors.grey[200],
                onPressed: () => _onLogicOperationPress("XOR"),
              ),
              _buildButton(
                "NOT",
                color: Colors.grey[200],
                onPressed: () => _onLogicOperationPress("NOT"),
              ),
              _buildButton(
                "NAND",
                color: Colors.grey[200],
                onPressed: () => _onLogicOperationPress("NAND"),
              ),
              _buildButton(
                "NOR",
                color: Colors.grey[200],
                onPressed: () => _onLogicOperationPress("NOR"),
              ),
            ],
          ),
          // 第四行：SHIFT操作
          Row(
            children: [
              _buildButton(
                "<<",
                color: Colors.grey[200],
                onPressed: () => _onLogicOperationPress("<<"),
              ),
              _buildButton(
                ">>",
                color: Colors.grey[200],
                onPressed: () => _onLogicOperationPress(">>"),
              ),
              _buildButton(
                "+/-",
                color: Colors.grey[200],
                onPressed: _onPlusMinusPress,
              ),
              _buildButton(
                "%",
                color: Colors.grey[200],
                onPressed: _onPercentPress,
              ),
            ],
          ),
          // 第五行：7、8、9、A
          Row(
            children: [
              _buildButton("7", onPressed: () => _onProgrammerDigitPress("7")),
              _buildButton("8", onPressed: () => _onProgrammerDigitPress("8")),
              _buildButton("9", onPressed: () => _onProgrammerDigitPress("9")),
              _buildButton("A", onPressed: () => _onProgrammerDigitPress("A")),
            ],
          ),
          // 第六行：4、5、6、B
          Row(
            children: [
              _buildButton("4", onPressed: () => _onProgrammerDigitPress("4")),
              _buildButton("5", onPressed: () => _onProgrammerDigitPress("5")),
              _buildButton("6", onPressed: () => _onProgrammerDigitPress("6")),
              _buildButton("B", onPressed: () => _onProgrammerDigitPress("B")),
            ],
          ),
          // 第七行：1、2、3、C
          Row(
            children: [
              _buildButton("1", onPressed: () => _onProgrammerDigitPress("1")),
              _buildButton("2", onPressed: () => _onProgrammerDigitPress("2")),
              _buildButton("3", onPressed: () => _onProgrammerDigitPress("3")),
              _buildButton("C", onPressed: () => _onProgrammerDigitPress("C")),
            ],
          ),
          // 第八行：0、.、D、E、F
          Row(
            children: [
              _buildButton("0", onPressed: () => _onProgrammerDigitPress("0")),
              _buildButton(".",
                  color: Colors.grey[100], // 使用灰色背景
                  onPressed: null), // 禁用小数点按钮
              _buildButton("D", onPressed: () => _onProgrammerDigitPress("D")),
              _buildButton("E", onPressed: () => _onProgrammerDigitPress("E")),
              _buildButton("F", onPressed: () => _onProgrammerDigitPress("F")),
            ],
          ),
          // 第九行：运算符号
          Row(
            children: [
              _buildButton(
                "+",
                color: Colors.orange[300],
                onPressed: () => _onOperationPress("+"),
              ),
              _buildButton(
                "-",
                color: Colors.orange[300],
                onPressed: () => _onOperationPress("-"),
              ),
              _buildButton(
                "×",
                color: Colors.orange[300],
                onPressed: () => _onOperationPress("×"),
              ),
              _buildButton(
                "÷",
                color: Colors.orange[300],
                onPressed: () => _onOperationPress("÷"),
              ),
              _buildButton(
                "=",
                color: Colors.orange[300],
                onPressed: _onEqualPress,
              ),
            ],
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        children: [
          // 模式切换按钮
          SafeArea(
            child: Container(
              padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
              alignment: Alignment.centerRight,
              child: PopupMenuButton<String>(
                child: Container(
                  padding: const EdgeInsets.symmetric(
                    horizontal: 20,
                    vertical: 10,
                  ),
                  decoration: BoxDecoration(
                    color: _currentMode == "程序员模式"
                        ? Colors.orange
                        : Colors.grey[200],
                    borderRadius: BorderRadius.circular(20),
                  ),
                  child: Text(
                    _currentMode,
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.normal, // 统一字体粗细
                      color: _currentMode == "程序员模式"
                          ? Colors.white
                          : Colors.black87,
                    ),
                  ),
                ),
                itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
                  PopupMenuItem<String>(
                    value: "标准模式",
                    child: Text(
                      "标准模式",
                      style: const TextStyle(
                        fontWeight: FontWeight.normal, // 统一字体粗细
                      ),
                    ),
                  ),
                  PopupMenuItem<String>(
                    value: "程序员模式",
                    child: Text(
                      "程序员模式",
                      style: const TextStyle(
                        fontWeight: FontWeight.normal, // 统一字体粗细
                      ),
                    ),
                  ),
                  PopupMenuItem<String>(
                    value: "汇率模式",
                    child: Text(
                      "汇率模式",
                      style: const TextStyle(
                        fontWeight: FontWeight.normal, // 统一字体粗细
                      ),
                    ),
                  ),
                ],
                onSelected: (String mode) {
                  setState(() {
                    _currentMode = mode;
                    _isProgrammerMode = mode == "程序员模式";
                    // 重置计算器状态
                    _onClearPress();
                  });
                },
              ),
            ),
          ),

          // 根据当前模式显示不同的内容
          Expanded(
            child: _currentMode == "汇率模式"
                ? const CurrencyConverterPage()
                : Column(
                    children: [
                      Expanded(
                        flex: 1,
                        child: Container(
                          padding: const EdgeInsets.all(16),
                          color: Colors.white,
                          child: _isProgrammerMode
                              ? _buildBaseMatrix()
                              : Column(
                                  mainAxisAlignment: MainAxisAlignment.end,
                                  crossAxisAlignment:
                                      CrossAxisAlignment.stretch,
                                  children: [
                                    // 历史区可滚动
                                    Expanded(
                                      child: SingleChildScrollView(
                                        reverse: true,
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.stretch,
                                          children: _history
                                              .map(
                                                (item) => Padding(
                                                  padding:
                                                      const EdgeInsets.only(
                                                    bottom: 8,
                                                  ),
                                                  child: Text(
                                                    item,
                                                    style: TextStyle(
                                                      fontSize: 24,
                                                      color: Colors.grey[600],
                                                    ),
                                                    textAlign: TextAlign.right,
                                                  ),
                                                ),
                                              )
                                              .toList(),
                                        ),
                                      ),
                                    ),
                                    // 当前过程
                                    Text(
                                      _expression,
                                      style: TextStyle(
                                        fontSize: 32,
                                        color: Colors.grey[600],
                                      ),
                                      textAlign: TextAlign.right,
                                    ),
                                    const SizedBox(height: 8),
                                    // 当前结果
                                    Text(
                                      _output,
                                      style: const TextStyle(
                                        fontSize: 48,
                                        color: Colors.black,
                                        fontWeight: FontWeight.bold,
                                      ),
                                      textAlign: TextAlign.right,
                                    ),
                                  ],
                                ),
                        ),
                      ),
                      Expanded(
                        flex: 2,
                        child: Container(
                          color: Colors.white,
                          child: _isProgrammerMode
                              ? _buildProgrammerKeypad()
                              : Container(
                                  padding: const EdgeInsets.all(16),
                                  child: Column(
                                    children: [
                                      // 第一行：内存功能按钮
                                      Row(
                                        children: [
                                          _buildButton(
                                            "MC",
                                            color: Colors.grey[200],
                                            onPressed: _onMemoryClear,
                                            fontSize: 16,
                                          ),
                                          _buildButton(
                                            "MR",
                                            color: _memoryEnabled
                                                ? Colors.grey[200]
                                                : Colors.grey[100],
                                            onPressed: _memoryEnabled
                                                ? _onMemoryRecall
                                                : null,
                                            fontSize: 16,
                                          ),
                                          _buildButton(
                                            "M+",
                                            color: Colors.grey[200],
                                            onPressed: _onMemoryAdd,
                                            fontSize: 16,
                                          ),
                                          _buildButton(
                                            "M-",
                                            color: Colors.grey[200],
                                            onPressed: _onMemorySubtract,
                                            fontSize: 16,
                                          ),
                                          _buildButton(
                                            "MS",
                                            color: Colors.grey[200],
                                            onPressed: _onMemoryStore,
                                            fontSize: 16,
                                          ),
                                        ],
                                      ),
                                      // 第二行：%、CE、C、退格
                                      Row(
                                        children: [
                                          _buildButton(
                                            "%",
                                            color: Colors.grey[200],
                                            onPressed: _onPercentPress,
                                          ),
                                          _buildButton(
                                            "CE",
                                            color: Colors.grey[200],
                                            onPressed: _onPartialClearPress,
                                          ),
                                          _buildButton(
                                            "C",
                                            color: Colors.grey[200],
                                            onPressed: _onClearPress,
                                          ),
                                          _buildButton(
                                            "←",
                                            color: Colors.grey[200],
                                            onPressed: _onBackspace,
                                          ),
                                        ],
                                      ),
                                      // 第三行：1/x、x²、√x、÷
                                      Row(
                                        children: [
                                          _buildButton(
                                            "1/x",
                                            color: Colors.grey[200],
                                            onPressed: _onReciprocal,
                                          ),
                                          _buildButton(
                                            "x²",
                                            color: Colors.grey[200],
                                            onPressed: _onSquare,
                                          ),
                                          _buildButton(
                                            "√x",
                                            color: Colors.grey[200],
                                            onPressed: _onSquareRoot,
                                          ),
                                          _buildButton(
                                            "÷",
                                            color: Colors.orange[300],
                                            onPressed: () =>
                                                _onOperationPress("÷"),
                                          ),
                                        ],
                                      ),
                                      // 第四行：7、8、9、×
                                      Row(
                                        children: [
                                          _buildButton(
                                            "7",
                                            onPressed: () => _onDigitPress("7"),
                                          ),
                                          _buildButton(
                                            "8",
                                            onPressed: () => _onDigitPress("8"),
                                          ),
                                          _buildButton(
                                            "9",
                                            onPressed: () => _onDigitPress("9"),
                                          ),
                                          _buildButton(
                                            "×",
                                            color: Colors.orange[300],
                                            onPressed: () =>
                                                _onOperationPress("×"),
                                          ),
                                        ],
                                      ),
                                      // 第五行：4、5、6、-
                                      Row(
                                        children: [
                                          _buildButton(
                                            "4",
                                            onPressed: () => _onDigitPress("4"),
                                          ),
                                          _buildButton(
                                            "5",
                                            onPressed: () => _onDigitPress("5"),
                                          ),
                                          _buildButton(
                                            "6",
                                            onPressed: () => _onDigitPress("6"),
                                          ),
                                          _buildButton(
                                            "-",
                                            color: Colors.orange[300],
                                            onPressed: () =>
                                                _onOperationPress("-"),
                                          ),
                                        ],
                                      ),
                                      // 第六行：1、2、3、+
                                      Row(
                                        children: [
                                          _buildButton(
                                            "1",
                                            onPressed: () => _onDigitPress("1"),
                                          ),
                                          _buildButton(
                                            "2",
                                            onPressed: () => _onDigitPress("2"),
                                          ),
                                          _buildButton(
                                            "3",
                                            onPressed: () => _onDigitPress("3"),
                                          ),
                                          _buildButton(
                                            "+",
                                            color: Colors.orange[300],
                                            onPressed: () =>
                                                _onOperationPress("+"),
                                          ),
                                        ],
                                      ),
                                      // 第七行：+/-、0、.、=
                                      Row(
                                        children: [
                                          _buildButton(
                                            "+/-",
                                            onPressed: _onPlusMinusPress,
                                          ),
                                          _buildButton(
                                            "0",
                                            onPressed: () => _onDigitPress("0"),
                                          ),
                                          _buildButton(
                                            ".",
                                            onPressed: _onDecimalPress,
                                          ),
                                          _buildButton(
                                            "=",
                                            color: Colors.orange[300],
                                            onPressed: _onEqualPress,
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                ),
                        ),
                      ),
                    ],
                  ),
          ),
        ],
      ),
    );
  }
}
